using System;
using System.Web;
using System.Web.UI;

namespace MetaSapiens.PageMethods
{
  /// <summary>
  /// HTTP module that enables PageMethods' support for HTTP POST.
  /// </summary>
  public class PageMethodsModule : IHttpModule
  {
    #region IHttpModule members

    void IHttpModule.Init(HttpApplication application)
    {
      application.BeginRequest += new EventHandler(Application_OnBeginRequest);
    }

    void IHttpModule.Dispose()
    {
    }

    #endregion IHttpModule members
  
    private static void Application_OnBeginRequest(Object sender, EventArgs e)
    {
      HttpContext context = HttpContext.Current;

      if ((context != null) && (context.Request != null) && IsSupportedHandler(context.Handler))
      {
        // Handle HTTP POST
        String newUrl = PageMethodsEngine.AddPostData(context.Request.RawUrl, context.Request);

        // Update the path
        context.RewritePath(newUrl, false);
      }
    }

    /// <summary>
    /// Add POST data only for <see cref="IHttpHandler">handlers</see> supported by PageMethods.
    /// </summary>
    /// <param name="handler"><see cref="IHttpHandler"/></param>
    /// <returns><see langword="true" /> if the current handler is supported by PageMethods, <see langword="false" /> otherwise.</returns>
    private static bool IsSupportedHandler(IHttpHandler handler)
    {
      if (handler == null)
        return true;
      if (handler is Page)
        return true;

      // Only Pages are supported at the moment. If other handlers are
      // supported too, they should be added here, maybe *.ashx.
      // Maybe a PageMethods BaseHandler class would be needed implementing
      // the call to PageMethodsEngine. Maybe this method must be changed
      // to check extension for *.aspx, *.ashx and other configurable extensions
      // that are mapped to a custom handler supporting PageMethods.

      return false;
    }
  }
}